import FYUtility from '../../Util/FYUtility';
import FYResMgr from './FYResMgr';


class _ResUtil {

    //设置玩家头像
    public SetHeadIcon(iconPath: string, iconSprite: cc.Sprite, ) {
        if (iconSprite == null) {
            console.error('iconSprite is null ');
            return;
        }

        //如果是网络图片
        if (FYUtility.CheckNetUrl(iconPath)) {
            this.LoadNetImage(iconPath, iconSprite);
            return;
        }

        //本地加载头像
        this.ChangeSprite(iconPath, iconSprite);
    }



    //加载网络图片
    public LoadNetImage(path: string, obj: cc.Sprite) {
        if (FYUtility.IsNullOrEmpty(path)) {
            console.warn("LoadNetImg Path Error:" + path);
            return;
        }

        if (!FYUtility.CheckNetUrl(path)) {
            return;
        }
        let index = path.lastIndexOf('/');
        let headUrl = path.slice(0, index) + '/0';
        cc.loader.load({ url: headUrl, type: 'jpg' }, (err, pic) => {
            if (err) {
                console.warn('LoadNetImg load error,error:' + err);
                return;
            }
            if (obj.node == null) {
                console.error('LoadNetImg load error>>>>>>>>obj.node==null')
                return;
            }
            let spriteFrame = new cc.SpriteFrame(pic);
            obj.spriteFrame = spriteFrame;
        });
    }

    //改变图片
    public async ChangeSprite(name: string, sprite: cc.Sprite) {
        if (sprite == null) {
            return;
        }

        if (FYUtility.IsNullOrEmpty(name)) {
            console.error('ChangeSprite name is Empty!')
            return;
        }

        if (sprite.spriteFrame != null && sprite.spriteFrame.name == name) {
            return;
        }

        let res: cc.SpriteFrame = await FYResMgr.Instance.LoadRes(name, cc.SpriteFrame);
        if (sprite.isValid) {
            sprite.spriteFrame = res;
        }
    }
}

export let ResUtil: _ResUtil = new _ResUtil();